import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores";
import MainLayout from "@/layouts/MainLayout.vue";

const routes = [
  // Auth routes (no layout)
  {
    path: "/auth",
    children: [
      {
        path: "login",
        name: "Login",
        component: () => import("@/pages/auth/LoginPage.vue"),
        meta: { requiresGuest: true, title: "Login" },
      },
      {
        path: "register",
        name: "Register",
        component: () => import("@/pages/auth/RegisterPage.vue"),
        meta: { requiresGuest: true, title: "Register" },
      },
      {
        path: "forgot-password",
        name: "ForgotPassword",
        component: () => import("@/pages/auth/ForgotPasswordPage.vue"),
        meta: { requiresGuest: true, title: "Reset Password" },
      },
      {
        path: "email-verification",
        name: "EmailVerification",
        component: () => import("@/pages/auth/EmailVerificationPage.vue"),
        meta: { title: "Email Verification" },
      },
    ],
  },
  // Main app routes (with layout)
  {
    path: "/",
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: "",
        name: "Home",
        component: () => import("@/pages/home/HomePage.vue"),
        meta: { title: "Social Dojo" },
      },
      {
        path: "training",
        name: "Training",
        component: () => import("@/pages/training/TrainingPage.vue"),
        meta: { title: "Training" },
      },
      {
        path: "training/character-select",
        name: "CharacterSelect",
        component: () => import("@/pages/training/CharacterSelectPage.vue"),
        meta: { title: "Select Character" },
      },
      {
        path: "training/scenario-select",
        name: "ScenarioSelect",
        component: () => import("@/pages/training/ScenarioSelectPage.vue"),
        meta: { title: "Select Scenario" },
      },
      {
        path: "training/chat",
        name: "TrainingChat",
        component: () => import("@/pages/training/TrainingChatPage.vue"),
        meta: { title: "Training Session" },
      },
      {
        path: "training/review",
        name: "TrainingReview",
        component: () => import("@/pages/training/TrainingReviewPage.vue"),
        meta: { title: "Training Review" },
      },
      {
        path: "training/session/:sessionId",
        name: "TrainingSession",
        component: () => import("@/pages/training/TrainingSessionPage.vue"),
        meta: { title: "Training Session" },
      },
      {
        path: "training/scenario/:scenarioId",
        name: "TrainingScenarioDetail",
        component: () => import("@/pages/training/ScenarioDetailPage.vue"),
        meta: { title: "Scenario Details" },
      },
      {
        path: "training/character/:characterId",
        name: "TrainingCharacterDetail",
        component: () => import("@/pages/training/CharacterDetailPage.vue"),
        meta: { title: "Character Details" },
      },
      {
        path: "community",
        name: "Community",
        component: () => import("@/pages/community/CommunityPage.vue"),
        meta: { title: "Community" },
      },
      {
        path: "community/post/:postId",
        name: "PostDetail",
        component: () => import("@/pages/community/PostDetailPage.vue"),
        meta: { title: "Post Details" },
      },
      {
        path: "profile",
        name: "Profile",
        component: () => import("@/pages/profile/ProfilePage.vue"),
        meta: { title: "Profile" },
      },
      {
        path: "profile/settings",
        name: "Settings",
        component: () => import("@/pages/profile/SettingsPage.vue"),
        meta: { title: "Settings" },
      },
      {
        path: "profile/favorites",
        name: "Favorites",
        component: () => import("@/pages/profile/FavoritesPage.vue"),
        meta: { title: "Favorites" },
      },
      {
        path: "profile/progress",
        name: "Progress",
        component: () => import("@/pages/profile/ProgressPage.vue"),
        meta: { title: "Learning Progress" },
      },
      {
        path: "profile/posts",
        name: "MyPosts",
        component: () => import("@/pages/profile/PostsPage.vue"),
        meta: { title: "My Posts" },
      },
      {
        path: "profile/edit",
        name: "EditProfile",
        component: () => import("@/pages/profile/EditProfilePage.vue"),
        meta: { title: "Edit Profile" },
      },
      {
        path: "profile/email-settings",
        name: "EmailSettings",
        component: () => import("@/pages/profile/EmailSettingsPage.vue"),
        meta: { title: "Email Settings" },
      },
      {
        path: "profile/privacy-settings",
        name: "PrivacySettings",
        component: () => import("@/pages/profile/PrivacySettingsPage.vue"),
        meta: { title: "Privacy Settings" },
      },
      {
        path: "profile/training-history",
        name: "TrainingHistory",
        component: () => import("@/pages/profile/TrainingHistoryPage.vue"),
        meta: { title: "Training History" },
      },
      {
        path: "profile/settings/account",
        name: "AccountSettings",
        component: () => import("@/pages/profile/AccountSettingsPage.vue"),
        meta: { title: "Account Settings" },
      },
      {
        path: "profile/settings/privacy",
        name: "ProfilePrivacySettings",
        component: () =>
          import("@/pages/profile/ProfilePrivacySettingsPage.vue"),
        meta: { title: "Privacy Settings" },
      },
      {
        path: "profile/activity",
        name: "ActivityHistory",
        component: () => import("@/pages/profile/ActivityHistoryPage.vue"),
        meta: { title: "Activity History" },
      },
      // Assessment routes
      {
        path: "assessment",
        name: "Assessment",
        component: () => import("@/pages/assessment/AssessmentPage.vue"),
        meta: { title: "Ability Assessment" },
      },
      {
        path: "assessment/result/:assessmentId",
        name: "AssessmentResult",
        component: () => import("@/pages/assessment/AssessmentResultPage.vue"),
        meta: { title: "Assessment Result" },
      },
      // Abilities routes
      {
        path: "abilities/radar",
        name: "AbilityRadar",
        component: () => import("@/pages/abilities/AbilityRadarPage.vue"),
        meta: { title: "Ability Radar" },
      },
      // Achievements routes
      {
        path: "achievements",
        name: "Achievements",
        component: () => import("@/pages/achievements/AchievementsPage.vue"),
        meta: { title: "Achievements" },
      },
      // Motivation routes
      {
        path: "motivation/daily-challenges",
        name: "DailyChallenges",
        component: () => import("@/pages/motivation/DailyChallengesPage.vue"),
        meta: { title: "Daily Challenges" },
      },
      // Community additional routes
      {
        path: "community/feed",
        name: "CommunityFeed",
        component: () => import("@/pages/community/CommunityFeedPage.vue"),
        meta: { title: "Community Feed" },
      },
      {
        path: "community/publish",
        name: "PublishPost",
        component: () => import("@/pages/community/PublishPage.vue"),
        meta: { title: "Publish Post" },
      },
      // Challenge routes
      {
        path: "challenge/:challengeId",
        name: "ChallengeDetail",
        component: () => import("@/pages/challenge/ChallengeDetailPage.vue"),
        meta: { title: "Challenge" },
      },
      // Notification routes
      {
        path: "notifications",
        name: "Notifications",
        component: () => import("@/pages/NotificationsPage.vue"),
        meta: { title: "Notifications" },
      },
      // Help and Info routes
      {
        path: "help",
        name: "Help",
        component: () => import("@/pages/HelpPage.vue"),
        meta: { title: "Help & Support" },
      },
      {
        path: "privacy-policy",
        name: "PrivacyPolicy",
        component: () => import("@/pages/PrivacyPolicyPage.vue"),
        meta: { title: "Privacy Policy" },
      },
      {
        path: "terms",
        name: "Terms",
        component: () => import("@/pages/TermsPage.vue"),
        meta: { title: "Terms of Service" },
      },
      {
        path: "about",
        name: "About",
        component: () => import("@/pages/AboutPage.vue"),
        meta: { title: "About Social Dojo" },
      },
      // Debug page (development only)
      {
        path: "debug",
        name: "Debug",
        component: () => import("@/pages/DebugPage.vue"),
        meta: { title: "API Debug Tool" },
      },
    ],
  },
  // Redirect old routes
  {
    path: "/login",
    redirect: "/auth/login",
  },
  {
    path: "/register",
    redirect: "/auth/register",
  },
  {
    path: "/home",
    redirect: "/",
  },
  {
    path: "/feed",
    redirect: "/community/feed",
  },
  {
    path: "/publish",
    redirect: "/community/publish",
  },
  {
    path: "/challenges",
    redirect: "/motivation/daily-challenges",
  },
  {
    path: "/profile/achievements",
    redirect: "/achievements",
  },
  // Additional redirects for common navigation patterns
  {
    path: "/training/scenarios",
    redirect: "/training/scenario-select",
  },
  {
    path: "/training/characters",
    redirect: "/training/character-select",
  },
  {
    path: "/daily-challenges",
    redirect: "/motivation/daily-challenges",
  },
  // 404 page
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/pages/NotFoundPage.vue"),
    meta: { title: "Page Not Found" },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore();

  // 性能监控：记录路由开始时间
  const routeStartTime = performance.now();

  // 确保用户状态已初始化
  if (!userStore.isAuthenticated) {
    userStore.initializeFromStorage();
  }

  // 设置页面标题
  if (to.meta?.title) {
    document.title = to.meta.title as string;
  }

  // 检查认证状态
  const requiresAuth = to.matched.some((record) => record.meta?.requiresAuth);
  const requiresGuest = to.meta?.requiresGuest;

  if (requiresAuth && !userStore.isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next({
      name: "Login",
      query: { redirect: to.fullPath },
    });
  } else if (requiresGuest && userStore.isAuthenticated) {
    // 需要游客状态但已登录，跳转到首页
    next({ name: "Home" });
  } else {
    // 预加载下一个可能访问的路由
    preloadNextRoutes(to, _from);
    next();
  }

  // 记录路由性能
  router.afterEach(() => {
    const routeEndTime = performance.now();
    const routeTime = routeEndTime - routeStartTime;

    if (import.meta.env.DEV) {
      console.log(`Route ${String(to.name)} took ${routeTime.toFixed(2)}ms`);
    }

    // 记录到性能日志
    recordRoutePerformance(String(to.name), routeTime);
  });
});

// 预加载相关路由
const preloadNextRoutes = (to: any, _from: any) => {
  const preloadMap: Record<string, string[]> = {
    Home: ["Training", "Community", "Profile", "Achievements"],
    Training: ["CharacterSelect", "ScenarioSelect", "TrainingChat"],
    CharacterSelect: ["ScenarioSelect", "TrainingChat"],
    ScenarioSelect: ["TrainingChat"],
    Community: ["PostDetail", "CommunityFeed", "PublishPost"],
    CommunityFeed: ["PostDetail", "PublishPost"],
    Profile: ["Settings", "Favorites", "Progress", "MyPosts"],
    Assessment: ["AssessmentResult"],
    Achievements: ["AbilityRadar"],
  };

  const routesToPreload = preloadMap[to.name as string];
  if (routesToPreload) {
    routesToPreload.forEach((routeName) => {
      const route = routes.find(
        (r) =>
          r.name === routeName ||
          r.children?.some((child) => child.name === routeName)
      );
      if (route) {
        // 预加载组件
        setTimeout(() => {
          if (route.component && typeof route.component === "function") {
            (route.component as () => Promise<any>)();
          }
        }, 100);
      }
    });
  }
};

// 记录路由性能
const recordRoutePerformance = (routeName: string, time: number) => {
  const performanceLog = {
    route: routeName,
    time,
    timestamp: Date.now(),
    userAgent: navigator.userAgent,
  };

  // 存储到本地存储（开发环境）
  if (import.meta.env.DEV) {
    const logs = JSON.parse(localStorage.getItem("routePerformance") || "[]");
    logs.push(performanceLog);

    // 只保留最近100条记录
    if (logs.length > 100) {
      logs.splice(0, logs.length - 100);
    }

    localStorage.setItem("routePerformance", JSON.stringify(logs));
  }
};

export default router;
